package com.pope.framework.triage.modular.service;

import com.pope.framework.constants.CompareEnum;
import com.pope.framework.core.util.DecimalUtil;
import com.pope.framework.core.util.ToolUtil;
import com.pope.framework.kernel.model.exception.ServiceException;
import com.pope.framework.triage.modular.dto.GradeCompareDto;
import com.pope.framework.triage.modular.dto.ValueDto;
import com.pope.framework.triage.modular.entity.GradeInfo;
import com.pope.framework.triage.modular.entity.GradeNorm;
import com.pope.framework.triage.modular.entity.TriageInfo;
import com.pope.framework.triage.modular.mapper.GradeInfoMapper;
import com.pope.framework.triage.modular.vo.GradeInfoVo;
import com.pope.framework.triage.modular.vo.GradeNormVo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;

import com.alibaba.druid.sql.ast.statement.SQLWithSubqueryClause.Entry;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 分诊级别信息表 服务实现类
 * </p>
 *
 * @author superpope
 * @since 2019-01-14
 */
@Service
@Transactional
public class GradeInfoService extends ServiceImpl<GradeInfoMapper, GradeInfo> {
	@Autowired
	private GradeNormService gradeNormService;
	
	@Autowired
	private TriageInfoService triageInfoService;
	
	public Integer insert(GradeInfoVo gradeInfoVo) {
		
		GradeInfo queryGradeInfo=new GradeInfo();
		queryGradeInfo.setDanger(gradeInfoVo.getDanger());
//		if(gradeInfoVo.getHospitalId()!=null) {
//			queryGradeInfo.setHospitalId(gradeInfoVo.getHospitalId());
//		}
		
		QueryWrapper<GradeInfo> queryWrapper=new QueryWrapper<>();
		queryWrapper.setEntity(queryGradeInfo);
		int count=this.count(queryWrapper);
		if(count>0) {
			throw new ServiceException("该分级的危急程度编号已存在，请重新确认！");
		}
		GradeInfo queryGradeInfo2=new GradeInfo();
		queryGradeInfo2.setName(gradeInfoVo.getName().trim());
//		if(gradeInfoVo.getHospitalId()!=null) {
//			queryGradeInfo2.setHospitalId(gradeInfoVo.getHospitalId());
//		}
		QueryWrapper<GradeInfo> queryWrapper2=new QueryWrapper<>();
		queryWrapper2.setEntity(queryGradeInfo2);
		int count2=this.count(queryWrapper2);
		if(count2>0) {
			throw new ServiceException("该分级的名称编号已存在，请重新确认！");
		}
		GradeInfo gradeInfo=new GradeInfo();
		BeanUtil.copyProperties(gradeInfoVo, gradeInfo);
		boolean flag=this.save(gradeInfo);
		if(!flag) {
			throw new ServiceException("保存失败，请重新确认");
		}
		saveGradeNormal(gradeInfoVo,gradeInfo);
		return gradeInfo.getId();
	}
	
	private void saveGradeNormal(GradeInfoVo gradeInfoVo,GradeInfo gradeInfo) {
		List<GradeNorm> gradeNorms=CollUtil.newArrayList();
		if(CollUtil.isNotEmpty(gradeInfoVo.getGradeNorms())) {
			for(GradeNormVo gradeNormVo:gradeInfoVo.getGradeNorms()) {
				GradeNorm gradeNorm=new GradeNorm();
				BeanUtil.copyProperties(gradeNormVo, gradeNorm);
				gradeNorm.setGradeId(gradeInfo.getId());
				gradeNorms.add(gradeNorm);
			}
			gradeNormService.saveBatch(gradeNorms);
		}
	}
	
	private void deleteGradeNormal(GradeInfo gradeInfo) {
		GradeNorm deleteGradeNorm=new GradeNorm();
		deleteGradeNorm.setGradeId(gradeInfo.getId());
		UpdateWrapper<GradeNorm> deleteGradeNormWrapper=new UpdateWrapper<>();
		deleteGradeNormWrapper.setEntity(deleteGradeNorm);
		gradeNormService.remove(deleteGradeNormWrapper);
	}
	public Integer modify(GradeInfoVo gradeInfoVo) {
	
		GradeInfo queryGradeInfo=new GradeInfo();
		queryGradeInfo.setDanger(gradeInfoVo.getDanger());
//		if(gradeInfoVo.getHospitalId()!=null) {
//			queryGradeInfo.setHospitalId(gradeInfoVo.getHospitalId());
//		}
		QueryWrapper<GradeInfo> queryWrapper=new QueryWrapper<>();
		queryWrapper.setEntity(queryGradeInfo);
		List<GradeInfo> gradeInfos=this.list(queryWrapper);
		if(CollUtil.isNotEmpty(gradeInfos)) {
			for(GradeInfo one:gradeInfos) {
				if(one.getDanger().equals(gradeInfoVo.getDanger())
						&& !one.getId().equals(gradeInfoVo.getId())) {
					throw new ServiceException("该分级的危急程度编号已存在，请重新确认！");
				}
			}
		}
		
		
		GradeInfo queryGradeInfo2=new GradeInfo();
		queryGradeInfo2.setName(gradeInfoVo.getName().trim());
//		if(gradeInfoVo.getHospitalId()!=null) {
//			queryGradeInfo2.setHospitalId(gradeInfoVo.getHospitalId());
//		}
		QueryWrapper<GradeInfo> queryWrapper2=new QueryWrapper<>();
		queryWrapper2.setEntity(queryGradeInfo2);
		List<GradeInfo> gradeInfos2=this.list(queryWrapper2);
		if(CollUtil.isNotEmpty(gradeInfos2)) {
			for(GradeInfo one:gradeInfos2) {
				if(one.getName().trim().equals(gradeInfoVo.getName().trim())
						&& !one.getId().equals(gradeInfoVo.getId())) {
					throw new ServiceException("该分级的名称编号已存在，请重新确认！");
				}
			}
		}
		
		
		
		GradeInfo gradeInfo=new GradeInfo();
		BeanUtil.copyProperties(gradeInfoVo, gradeInfo);
		gradeInfo.setCreatetime(null);
		gradeInfo.setCreateMan(null);
		boolean flag=this.updateById(gradeInfo);
		if(!flag) {
			throw new ServiceException("修改失败，请重新确认");
		}
		deleteGradeNormal(gradeInfo);
		saveGradeNormal(gradeInfoVo,gradeInfo);
		
		return gradeInfo.getId();
	}
	
	public void delete(Integer id) {
		GradeInfo gradeInfo=this.getById(id);
		if(gradeInfo==null) {
			throw new ServiceException("该分级信息不存在，请重新确认!");
		}
		QueryWrapper<TriageInfo> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq("AUTO_GRADE", id);
		queryWrapper.or();
		queryWrapper.eq("COMING_GRADE", id);
		queryWrapper.or();
		queryWrapper.eq("CHANGE_GRADE", id);
		int count=triageInfoService.count(queryWrapper);
		if(count>0) {
			throw new ServiceException("该分级信息已被分诊记录使用，您无法删除该分级信息！");
		}
		this.deleteGradeNormal(gradeInfo);
		
		boolean flag=this.removeById(id);
		if(!flag) {
			throw new ServiceException("删除失败，请重新确认");
		}
	}
	
	
	public GradeInfo compare(GradeCompareDto gradeCompareInfo) {
	
		GradeInfo queryGradeInfo=new GradeInfo();
		
//		queryGradeInfo.setHospitalId(gradeCompareInfo.getHospitalId());
//		
		QueryWrapper<GradeInfo> queryGradeInfoWrapper=new QueryWrapper<>();
		queryGradeInfoWrapper.setEntity(queryGradeInfo);
		queryGradeInfoWrapper.orderByAsc("DANGER");
	    List<GradeInfo> gradeInfos =this.list(queryGradeInfoWrapper);
	    if(CollUtil.isNotEmpty(gradeInfos)) {
	    	for(GradeInfo gradeInfo:gradeInfos) {
	    		boolean booleanEgg=true;
	    		if(ToolUtil.toInt(gradeInfo.getEgg(),0)!=ToolUtil.toInt(gradeCompareInfo.getMyocardialInfarction(), 0)) {
	    			booleanEgg=false;
	    		}
	    		GradeNorm queryGradeNorm=new GradeNorm();
	    		queryGradeNorm.setGradeId(gradeInfo.getId());
	    		QueryWrapper<GradeNorm> queryGradeNormWrapper=new QueryWrapper<>();
	    		queryGradeNormWrapper.setEntity(queryGradeNorm);
	    		
	    		List<GradeNorm> gradeNorms=gradeNormService.list(queryGradeNormWrapper);
	    		if(CollUtil.isNotEmpty(gradeNorms) && CollUtil.isNotEmpty(gradeCompareInfo.getValues())) {
	    			boolean find=comare(gradeCompareInfo,gradeNorms);
	    			if(find || booleanEgg) {
	    				return gradeInfo;
	    			}
	    		}
	    		
	    	}
	    }
	    return null;
	}
	
	/**
	 * 1.指标与指标之间是或的关系,允许重复添加同一个指标，取并集3如果取了多个集合，取危急程度最高的一个
	 * @param gradeCompareInfo
	 * @param gradeNorms
	 * @return
	 */
	private boolean comare(GradeCompareDto gradeCompareInfo,List<GradeNorm> gradeNorms) {
		Map<String,List<GradeNorm>> groupGradeNorm=CollUtil.newHashMap();
		Map<String,BigDecimal> mapValueDto=CollUtil.newHashMap();
		for(GradeNorm gradeNorm:gradeNorms) {//体征公式数据
			if(groupGradeNorm.containsKey(gradeNorm.getNormId())) {
				groupGradeNorm.get(gradeNorm.getNormId()).add(gradeNorm);
			}else {
				groupGradeNorm.put(gradeNorm.getNormId(), CollUtil.newArrayList());
				groupGradeNorm.get(gradeNorm.getNormId()).add(gradeNorm);
			}
		}
		if(CollUtil.isNotEmpty(gradeCompareInfo.getValues())) {
			for(ValueDto valueDto:gradeCompareInfo.getValues()) {
				mapValueDto.put(valueDto.getCode(), valueDto.getValue());
			}
		}
		Map<String,Boolean> mapBoolean=CollUtil.newHashMap();
		for(Map.Entry<String, BigDecimal> value:mapValueDto.entrySet()) {
			List<GradeNorm> listGradeNorm=groupGradeNorm.get(value.getKey());
			Boolean compareResult=comare(value.getValue(),listGradeNorm);
			mapBoolean.put(value.getKey(), compareResult);
		}
		for(Map.Entry<String, Boolean> map:mapBoolean.entrySet()) {
			if(map.getValue()) {
				return true;
			}
		}
		return false;
//		
//		for(ValueDto valueDto:gradeCompareInfo.getValues()) {//生命体征
//			for(GradeNorm gradeNorm:gradeNorms) {//体征公式数据
//				if(valueDto.getCode().equals(gradeNorm.getNormId())) {
//					if(CompareEnum.GT.getCode().equals(gradeNorm.getCompare())) {//大于
//    					if(DecimalUtil.toDecimal(valueDto.getValue()).compareTo(DecimalUtil.toDecimal(gradeNorm.getValue1()))==1){
//    						return false;
//    					}
//    				}else if(CompareEnum.GT.getCode().equals(gradeNorm.getCompare()))
//					else if(CompareEnum.LT.getCode().equals(gradeNorm.getCompare())) {//小于
//    					if(DecimalUtil.toDecimal(valueDto.getValue()).compareTo(DecimalUtil.toDecimal(gradeNorm.getValue1()))!=0){
//    						return false;
//    					}
//    				}else if(CompareEnum.EQ.getCode().equals(gradeNorm.getCompare())) {//等于
//    					if(DecimalUtil.toDecimal(valueDto.getValue()).compareTo(DecimalUtil.toDecimal(gradeNorm.getValue1()))!=-1){
//    						return false;
//    					}
//    				}else if(CompareEnum.RANGE.getCode().equals(gradeNorm.getCompare())) {//范围
//    					if(DecimalUtil.toDecimal(valueDto.getValue()).compareTo(DecimalUtil.toDecimal(gradeNorm.getValue1()))!=-1
//    							&& DecimalUtil.toDecimal(valueDto.getValue()).compareTo(DecimalUtil.toDecimal(gradeNorm.getValue2()))!=1){
//    						
//    					}else {
//    						return false;
//    					}
//    				}
//				}
//			}
//			
//		}
//		return true;
	}
	
	private boolean comare(BigDecimal value ,List<GradeNorm> gradeNorms) {
		value=DecimalUtil.toDecimal(value);
		if(CollUtil.isEmpty(gradeNorms)) {
			return true;
		}
		
		for(GradeNorm gradeNorm:gradeNorms) {
			if(CompareEnum.GT.getCode().equals(gradeNorm.getCompare())) {
				if(value.compareTo(DecimalUtil.toDecimal(gradeNorm.getValue1()))!=1) {
					return false;
				}
			}else if(CompareEnum.GT_EQ.getCode().equals(gradeNorm.getCompare())) {
				if(value.compareTo(DecimalUtil.toDecimal(gradeNorm.getValue1()))==-1) {
					return false;
				}
				
			}else if(CompareEnum.LT.getCode().equals(gradeNorm.getCompare())) {
				if(value.compareTo(DecimalUtil.toDecimal(gradeNorm.getValue1()))!=-1) {
					return false;
				}
			}else if(CompareEnum.LT_EQ.getCode().equals(gradeNorm.getCompare())) {
				if(value.compareTo(DecimalUtil.toDecimal(gradeNorm.getValue1()))==1) {
					return false;
				}
			}else if(CompareEnum.RANGE_ALL_CLOSE.getCode().equals(gradeNorm.getCompare())) {
				if(value.compareTo(DecimalUtil.toDecimal(gradeNorm.getValue1()))!=-1
						&& value.compareTo(DecimalUtil.toDecimal(gradeNorm.getValue2()))!=1) {
					
				}else {
					return false;
				}
				
			}else if(CompareEnum.RANGE_ALL_OPEN.getCode().equals(gradeNorm.getCompare())) {
				if(value.compareTo(DecimalUtil.toDecimal(gradeNorm.getValue1()))==1
						&& value.compareTo(DecimalUtil.toDecimal(gradeNorm.getValue2()))==-1) {
					
				}else {
					return false;
				}
			}else if(CompareEnum.RANGE_LEFT_OPEN.getCode().equals(gradeNorm.getCompare())) {
				if(value.compareTo(DecimalUtil.toDecimal(gradeNorm.getValue1()))==1
						&& value.compareTo(DecimalUtil.toDecimal(gradeNorm.getValue2()))!=-1) {
					
				}else {
					return false;
				}
			}else if(CompareEnum.RANGE_RIGHT_OPEN.getCode().equals(gradeNorm.getCompare())) {
				if(value.compareTo(DecimalUtil.toDecimal(gradeNorm.getValue1()))!=-1
						&& value.compareTo(DecimalUtil.toDecimal(gradeNorm.getValue2()))==-1) {
					
				}else {
					return false;
				}
			}
		}
		return true;
	}
}
